<template>
  <div class="detail-form" v-if="loadingFinish" >
    <Form :model="formInfo" ref="formInfo" class="ivu-form-no-margin-bottom form" :rules="rule" :label-width="120">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border: none">
          <FormItem prop="travelStandardCode" label="差标编码">
            <Input
              v-model="formInfo.travelStandardCode"
              :maxlength="50"
              style="width: 100%"
              :disabled="true"
              placeholder="系统自动生成无需输入"
              clearable
            ></Input>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="travelStandardName" label="差标名称">
            <Input placeholder="请输入差标名称" clearable :disabled="disabled" v-model.trim="formInfo.travelStandardName" :maxlength="50" style="width: 100%"></Input>
          </FormItem>
        </Col> 
        <Col span="12" style="border: none">
          <FormItem prop="isApplyBill" :label-width="130" label="是否需要申请单">
            <i-switch :disabled="disabled" :true-value="'1'" :false-value="'0'" v-model="formInfo.isApplyBill">
              <span slot="open">是</span>
              <span slot="close">否</span>
            </i-switch>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="isBudget" label="是否预算管控">
            <i-switch :disabled="disabled" :true-value="'1'" :false-value="'0'" v-model="formInfo.isBudget">
              <span slot="open">是</span>
              <span slot="close">否</span>
            </i-switch>
          </FormItem>
        </Col>
        <Col span="12" style="border: none" v-if="isPlatformAdmin">
          <FormItem prop="tenantCode" label="所属租户">
            <Select
              :disabled="!!formInfo.id"
              label-in-value
              filterable
              :value="formInfo.tenantCode"
              style="width: 100%"
              clearable
              @on-change="
                ({ label = '', value = '' } = {}) => {
                  formInfo.tenantCode = value.trim();
                  formInfo.tenantName = label.trim();
                }
              "
            >
              <Option v-for="tenant in tenantList" :value="tenant.tenantCode" :key="tenant.id">
                {{ tenant.tenantName }}
              </Option>
            </Select>
          </FormItem>
        </Col> 
        <Col span="12" style="border: none">
          <FormItem prop="ouNames" label="归属公司">
            <Input placeholder="请输入归属公司" clearable :disabled="disabled" v-model.trim="formInfo.ouNames" :maxlength="50" style="width: 100%"></Input>
          </FormItem>
        </Col> 
        <Col span="12" style="border: none" v-if="formInfo.id">
          <FormItem prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="formInfo.enabled" size="small">
              <Radio :label="'1'">
                <span>{{ $t('common.enable') }}</span>
              </Radio>
              <Radio :label="'0'">
                <span>{{ $t('common.disable') }}</span>
              </Radio>
            </RadioGroup>
          </FormItem>
        </Col>
     
        <Col span="24" style="border: none">
          <FormItem :label="$t('common.describe')">
            <Input
            placeholder="请输入描述"
              type="textarea"
              :rows="1"
              v-model="formInfo.remark"
              :maxlength="100"
              style="width: 100%"
              clearable
            ></Input>
          </FormItem>
        </Col>
      </Row>
      <Card style="width:100%">
        <p slot="title" class="form-title">
          各产品差标配置
        </p>
        <Tabs v-model="tabVal">
          <TabPane v-for="item in productList" v-bind:key="item.key" :label="item.title" :name="item.key">
            <component :is="item.key"  :disabled="disabled" v-model="formInfo[item.key+'']"></component>
          </TabPane>
        </Tabs>
      </Card>
    </Form>
  </div>
</template>
<script>
import tenantAPI from "@/api/tenantApi.js";
import { apiStandardAdd, apiStandardQueryDetail, apiStandardUpdate } from '@api/trip/standard/standard.js';
import debounce from "lodash/debounce";
import { mapGetters } from "vuex";
export default {
  name: 'StandardDetail',
  components: {
    train: () => import('./train.vue'),
    airplane: () => import('./airplane.vue'),
    hotel: () => import('./hotel.vue'),
    car: () => import('./car.vue')
  },
  props: {
    // * 差标ID
    id: {
      type: String, 
    },
    disabled:{
      type:Boolean,
      default:false, 
      required: false,
    }
  },
  data() {
    const trainValidate = (rule, value, callback) => { 
      if (value.crtSeatRestrict === '' && value.chsrSeatRestrict === '') {
        callback(new Error('请选择火车的坐席限制')); 
      }else {
        callback();
      }
    };
    return { 
      loadingFinish:false,
      tabVal: 'train', // 产品选项卡
      tenantList: [], // 租户列表
      // tab 选项卡
      productList: [
        {
          title: '火车',
          key: 'train',
          data: {
          //  tenantCode;
          //  travelStandardId; 差标ID
          //    travelStandardName; 差标名称
          //   crtSeatRestrict; 普通坐席限制,普通列车：硬座、硬卧、软座、二等软座、一等软座、软卧、高级软卧
          //    chsrSeatRestrict; 高铁/动车坐席限制 高铁动车：软座、软卧、二等座、二等卧、优选一等座、一等座、一等卧、商务座、特等座
          //   regionalRestrict; 城市管控
          //    dateRestrict; 日期管控
          //    transferRestrict; 中转管控
          //    standbyRestrict; 候补管控 
          }
        },
        {
          title: '酒店',
          key: 'hotel'
        },
        {
          title: '飞机',
          key: 'airplane'
        },
        {
          title: '用车',
          key: 'car'
        }
      ],
      formInfo: {
        // 差标编码
        travelStandardCode: '',
        // 差标名称
        travelStandardName: '',
        // customerCode 客户编码
        // customerName 客户名称
        // ouCodes 客商编码
        // ouNames 客商名称 
        ouNames:'',//
        isApplyBill: '0', // 是否需要申请单
        isBudget:'0', // 是否预算管控
        // 所属租户
        // tenantCode: '',
        // tenantName: '',
        //差标状态
        enabled: '1',
        //描述
        remark: '',
        train:{
          crtSeatRestrict:'',
          chsrSeatRestrict:'',
          regionalRestrict:'1',
          dateRestrict:'0',
          transferRestrict:'0',
          standbyRestrict:'0',
        }
      },
      rule: {
        travelStandardName: [{ required: true, message: '请输入差标名称', trigger: 'blur' }], 
        isApplyBill:[{ required: true, message: '请选择是否需要申请单', trigger: 'blur' }],// 是否需要申请单
        isBudget:[{ required: true, message: '请选择是否需要预算管控', trigger: 'blur' }], // 是否预算管控 
        'train':[{ required: true, validator: trainValidate, trigger: 'blur' }], //  
      },
      actions: [
        {
          /**
            text: "按钮label",
            theme: "warning",
            icon: "plus-round",
            action: "actionName1", //可以通过 SetActionsState  actionName1 的 state 来设置这个按钮是否 loading
        */
          text: this.$t('common.save'),
          theme: 'primary',
          action:"save",
          handle: debounce(()=>this.handleSave(),300),
          loading: false
        },
        {
          text: this.$t('common.close'),
          handle: () => {
            this.$emit('Close')
          }
        }
      ]
    }
  },
  computed: { 
    ...mapGetters(['isPlatformAdmin']), 
  },
  created: function() {
    this.tenantList = []
    this.$Spin.show({
        render: (h) => {
            return h('div', [
                h('Icon', {
                    'class': 'spin-icon-load',
                    props: {
                        type: 'ios-loading',
                        size: 18
                    }
                }),
                h('div', '加载中...')
            ])
        }
    });
    //#region  sidelipPage 配置
    if (this.id) {
      this.$emit('SetTitle', '编辑差标配置')
    } else {
      this.$emit('SetTitle', '新增差标配置')
    }
    this.$emit('SetPageWidth', 700)
    this.$emit('SetPageActions', this.actions)
    //#endregion
    this.init() 
  },
  mounted: function() {},
  methods: {  
    init() { 
      if (this.id) {
        // 查询详情数据
        apiStandardQueryDetail({id:this.id}).then(res => {
          console.log('res :>> ', res);
          this.formInfo = Object.assign({}, res.data) 
          this.$set(this.formInfo,'train',res.data['train']); 
          this.$Spin.hide();
          this.loadingFinish = true;  
        })
      } else {
        this.$Spin.hide();
        this.loadingFinish = true;  
      }
      if(this.isPlatformAdmin){ 
         /**
         * 加载所有租户
         */
         tenantAPI.queryTenantList().then(data => {
          // const {tenantName ,tenantCode,id }
          this.tenantList = data
            
        })
        this.$set(this.formInfo,'tenantCode',this.formInfo?.tenantCode);
        this.$set(this.rule,'tenantCode',[{ required: true, message: '请选择所属租户', trigger: 'blur' }]); 
      }
    },
    handleSave() {
      this.$refs['formInfo'].validate(valid => {
        if (valid) {
          this.actions[0].loading = true
          if (this.formInfo.id) {
            let param = this.formInfo
            apiStandardUpdate(param)
              .then(data => {
                this.actions[0].loading = false
                if (data.code === "0") {
                  this.$message.success({
                    content: '保存成功',
                    duration: 3
                  });
                  this.$emit('Close', true); 
                } else {
                  this.$message.error({
                    content: data.message || "保存失败",
                    duration: 3
                  });
                }  
              })
              .catch(data => {
                this.actions[0].loading = false
              })
          } else {
            let param = this.formInfo; 
            apiStandardAdd(param)
              .then(data => { 
                this.actions[0].loading = false 
                if (data.code === "0") {
                  this.$message.success({
                    content: '保存成功',
                    duration: 3
                  });
                  this.$emit('Close', true); 
                } else {
                  this.$message.error({
                    content: data.message || "保存失败",
                    duration: 3
                  });
                } 
              })
              .catch(data => {
                this.actions[0].loading = false
              })
          } 
        }
      })
    },
 
  }
}
</script>
<style scoped lang="less">
.detail-form {
  background: #f4f6fd;
  .form {
    background: #fff;
    padding: 24px 24px 12px 24px;
    .ivu-row {
      margin-bottom: 0px;
      .last-item {
        margin-bottom: 0px;
      }
    }
    .form-title {
      display: block;
      font-size: 16px;
      color: #333333;
      letter-spacing: 0;
      font-weight: 600;
    }
  }
}
</style>
